package com.wxxymaker.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Soft
 * @Date: 2018/6/17 23:47
 * @Desc: ip记录
 */
public class PathIPLog extends HandlerInterceptorAdapter {
    private static final Logger log = LoggerFactory.getLogger(PathIPLog.class);
    private long   start = 0;
    private String path  = "";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        start = System.currentTimeMillis();

        String address = request.getRemoteAddr();
        String host    = request.getRemoteHost();
        int    port    = request.getRemotePort();

        StringBuffer url   = request.getRequestURL();
        String       query = request.getQueryString();
        if (query == null) {
            path = url.toString();
        } else {
            path = url.append("?").append(query).toString();
        }

        log.info("### 访问Host: {}:{} 访问IP: {}", host, port, address);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        long end = System.currentTimeMillis();
        log.info("*** 请求路径: {} 耗时: {}ms", path, end - start);
    }
}
